package com.ibbi.admin.client.session;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.ibbi.admin.client.rpc.Services;

import corelib.client.Asserts;
import corelib.client.GwtUtil;
import corelib.client.cookie.SessionCookie;
import corelib.client.cookie.SessionCookieSetting;
import corelib.client.delegate.CompleteCallback;

public final class SessionManager {
	
	private static LoginHandler loginHandler;
	
	public static void init(LoginHandler loginHandler, final CompleteCallback callback) {
		Asserts.notNull(SessionManager.loginHandler = loginHandler);
		SessionCookie.init(new SessionCookieSetting()
					 .setName("ibbi.admin.session")
					 .setPath("/")
					 .setLifeTimeDays(30)
		);
		
		String oldPassport = SessionCookie.getInstance().get();
		if (oldPassport != null) {
			renewSession(oldPassport, callback);
		}
		else {
			loginAndRun(callback);
		}
	}
	
	public static void logout(){
		clearSession();
		GwtUtil.reloadPage();
	}
	
	public static String getPassport(){
		return SessionCookie.getInstance().get();
	}
	
	public static void renewSession(String passport, final CompleteCallback callback){
		Services.LogInService.LogInWithPassport(passport, new AsyncCallback<Session>() {
			@Override
			public void onSuccess(Session sessioin) {
				resetSession(sessioin);
				callback.onCompleted();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				clearSession();
				loginAndRun(callback);
			}
		});
	}
	
	public static void resetSession(Session session){
		Session.Current = session;
		SessionCookie.getInstance().put(session.getPassport());
	}
	
	public static void clearSession() {
		Session.Current = null;
		SessionCookie.getInstance().put(null);
	}
	
	private static void loginAndRun(final CompleteCallback callback) {
		loginHandler.login(new LoginListener() {
			@Override
			public void onSuccess(Session token) {
				resetSession(token);
				callback.onCompleted();
			}
		});
	}
}
